package com.whj.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.whj.domain.constants.SystemCharConstants;
import com.whj.domain.entity.Article;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.mapper.ArticleMapper;
import com.whj.service.ArticleService;
import com.whj.utils.RedisCache;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/28 - 05 - 28 - 15:41 
 * @Description: com.whj.job
 */

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 定时任务，每隔一段时间（一分钟）更新redis 中的数据
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void UpdateViewCount() {

        System.out.println("定时任务执行");
        // 获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemCharConstants.ARTICLE_VIEW_COUNT);
        UpdateWrapper<Article> wrapper;
        for (Map.Entry<String, Integer> entry : viewCountMap.entrySet()) {
            wrapper = new UpdateWrapper<>();
            if (!Strings.isBlank(entry.getKey())) {
                wrapper.eq("id", Long.parseLong(entry.getKey()));
                wrapper.set("view_count", entry.getValue().longValue());
                articleMapper.update(null, wrapper);
            }
        }
    }
}
